<?php
/**
 * 文件名：members.mod.php
 * 版本号：1.0
 * 最后修改时间：2006年7月18日 21:00:05
 * 作者：狐狸<foxis@qq.com>
 * 功能描述：用户组操作模块
 */
if(!defined('IN_JISHIGOU'))
{
    exit('invalid request');
}

class ModuleObject extends MasterObject
{
	
	var $ID = 0;


	
	var $ImagePath;


	
	function ModuleObject($config)
	{
		$this->MasterObject($config);


		if(isset($this->Get['id']))
		{
			$this->ID = (int)$this->Get['id'];
		}elseif(isset($this->Post['id']))
		{
			$this->ID = (int)$this->Post['id'];
		}


		$_GET['rmod']='my';
		if(MEMBER_ID > 0) {
			$this->IsAdmin = $this->MemberHandler->HasPermission('member','admin');
		}

		$this->Execute();
	}

	
	function Execute()
	{

		ob_start();
		switch($this->Code)
		{

			case 'step1':
				$this->Step1();
				break;
			case 'do_step1':
				$this->DoStep1();
				break;
			case 'step2':
				$this->Step2();
				break;
			case 'do_step2':
				$this->DoStep2();
				break;
			case 'verify':
				$this->Verify();
				break;
			case 'doregister':
				$this->DoRegister();
				break;

			default:
				$this->Register();
				break;
		}
		$Contents=ob_get_clean();
		$this->ShowBody($Contents);
	}

	function verify()
	{
		$key=(string) trim($this->Get['key']);
		$uid=(int) $this->Get['uid'];
		if (empty($key)) $this->Messager("验证字符串不能为空",null);
		if(strlen($key)!=16)$this->Messager("验证字符长度不符合标准，请检查。",null);
		$this->DatabaseHandler->SetTable(TABLE_PREFIX.'member_validate');
		$row=$this->DatabaseHandler->Select('',"`key`='{$key}' and `uid`='{$uid}'");
		if ($row==false)$this->messager("验证已过期或者验证信息不符合要求",null);
		if ($row['uid']!=$uid)$this->messager("验证用户ID和你的用户ID不符合，验证失败。",null);
		if($row['status']=='1')$this->Messager('您已经验证过了，不需要重复验证。',null);
		$data=array();
		$data['verify_time']=time();
		$data['status']=1;
		$this->DatabaseHandler->Update($data,"`key`='{$key}' and `uid`='{$uid}'");

				$sql = "delete from `".TABLE_PREFIX."member_validate` where `uid`='{$uid}' and `status`=0";
		$this->DatabaseHandler->Query($sql);


		$data=array();
		$data['role_id']=$row['role_id'];

		$this->DatabaseHandler->SetTable(TABLE_PREFIX.'members');
		$this->DatabaseHandler->Update($data,"uid={$row['uid']}");
		$this->Messager("验证成功，您现在可以正常体验本网站了",'?');

		$this->PromotionLogic->Register();
		$this->Messager("验证成功，您现在可以正常体验本网站了",'?');
	}


	
	function Register()
	{
		extract($this->Get);

		$action="index.php?mod=member&code=doregister";
		if ($this->Config['invite_enable']) {
			if(!$this->Code) {
								if ($this->Config['invite_by_admin']) {
					if (false === ($invite_admin_uids = cache('misc/invite-admin_uids',-1))) {
						
						$sql = "select `uid` from `".TABLE_PREFIX."members` where `role_type`='admin'";
						$query = $this->DatabaseHandler->Query($sql);
						$invite_admin_uids = array();
						while ($row = $query->GetRow())
						{
							$invite_admin_uids[$row['uid']] = $row['uid'];
						}

						cache($invite_admin_uids);
					}
					$invite_admin_uid = array_rand($invite_admin_uids);
					
										if($this->Get['uid']){
						$invite_admin_uid = $this->Get['uid'];
					}
					
					$sql = "select `uid`,`invitecode` from `".TABLE_PREFIX."members` where `uid`='{$invite_admin_uid}'";
					$query = $this->DatabaseHandler->Query($sql);
					$invite_admins = $query->GetRow();
					if($invite_admins && $invite_admins['invitecode']) {
						$this->Messager(null,"{$this->Config['site_url']}/index.php?mod=member&code=".urlencode($invite_admins['uid']."|".$invite_admins['invitecode']));
					} else {
						cache('misc/invite-admin_uids',0);
					}
				}

				$this->Messager("非常抱歉，本站目前需要有邀请链接才能注册。",null);
			} else {
				$check_result = $this->_checkInvite($this->Code);
				if(!$check_result) {
					$this->Messager("对不起，您访问的邀请链接不正确或者因邀请数已满而失效，请重新与邀请人索取链接。",null);
				}
			}
			$sql = "select `uid`,`ucuid`,`username`,`nickname`,`face_url`,`face` from `".TABLE_PREFIX."members` where `uid`='{$check_result['uid']}'";
			$query = $this->DatabaseHandler->Query($sql);
			$inviter_member = $query->GetRow();
			if($inviter_member) {
				$inviter_member['face'] = face_get($inviter_member);
			}
			$action .= "&invite_code=" . urlencode($this->Code);


			if (MEMBER_ID > 0) {
				$this->Messager("您已经是注册用户，无需再注册！您可以将地址栏中的网址复制给好友，邀请其注册并关注你。",null);
			}
		}

		if(MEMBER_ID != 0 AND false == $this->IsAdmin)
		{
			$this->Messager('您已经是注册用户，无需再注册！',-1);
		}
		if($this->CookieHandler->GetVar('referer')=='')
		{
			$this->CookieHandler->Setvar('referer',referer());
		}
		include ROOT_PATH . 'include/lib/form.han.php';
		$question_select=FormHandler::Select('question',ConfigHandler::get('member','question_list'),0);
		$this->Title="注册新用户";
		include $this->TemplateHandler->Template('member_register');
	}


	
	function DoRegister()
	{
		$timestamp = time();
		$datas = array();


		if ($this->Config['invite_enable'])
        {

			if(!$this->Code)
            {
				$this->Messager("非常抱歉，本站目前需要有好友邀请链接才能注册。<br><br>看看<a href=\"?mod=topic&code=top\">达人榜</a>中有没有你认识的人，让他给你发一个好友邀请。",null);
			}

			$check_result = $this->_checkInvite();
			if(!$check_result)
            {
				$this->Messager("对不起，您访问的邀请链接不正确或者因邀请数已满而失效，请重新与邀请人索取链接。",null);
			}

						$datas['invitecode'] = substr(md5(@implode("\t",(array) $check_result) . random(16)),0,16);
			$datas['follow_count'] = 1;
		}

		if(true === UCENTER) 		{
						include_once(ROOT_PATH . 'uc_client/client.php');

		}

		unset($this->Post['role_id']);
		if($this->Post['username']=="" || $this->Post['nickname']=="") {
			$this->Messager("用户名或昵称不能为空",-1);
		}
		$this->Post['username'] = strip_tags($this->Post['username']);
		$this->Post['nickname'] = strip_tags($this->Post['nickname']);
		if(strlen($this->Post['username'])<3 or strlen($this->Post['username'])>15) {
			$this->Messager("用户名必须在3至15个字节以内",null);
		}
		if(strlen($this->Post['nickname'])<3 or strlen($this->Post['nickname'])>15) {
			$this->Messager("昵称必须在3至15个字节以内",null);
		}
        if(is_numeric($this->Post['username']))
        {
            $this->Messager("用户名不能全部为数字");
        }
		if ($filter_msg = filter($this->Post['username'])) {
			$this->Messager("用户名 ".$filter_msg,null);
		}
		if ($filter_msg = filter($this->Post['nickname'])) {
			$this->Messager("昵称 ".$filter_msg,null);
		}
		if (!preg_match("~^[\w\d\_]+$~i", $this->Post['username'])) {
			$this->Messager("用户名只允许字母和数字",null);
		}
        if(preg_match('~[\`\~\!\@\$\^\*\/\&\?\-\.\#\%\+\=\[\]\{\}\|\\\\]+~',$this->Post['nickname']))
        {
            $this->Messager("昵称中不能包含“-” “.”等特殊符号",null);
        }

				$censoruser = ConfigHandler::get('user','forbid');
		$censoruser .= "topic
index
admin
ajax
login
member
profile
tag
get_password
report
weather
master
setting
wap
include
cache
data
api
error_log
iis_rewrite
images
install
modules
templates
uc_client
backup
imjiqiren
sms
qqwb
url";
		$censorexp = '/^('.str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($censoruser = trim($censoruser)), '/')).')$/i';
		if($censoruser && @preg_match($censorexp, $this->Post['username'])) {
			$this->Messager("用户名被保留，禁止注册",-1);
		}
        if($censoruser && @preg_match($censorexp, $this->Post['nickname'])) {
			$this->Messager("昵称被保留，禁止注册",-1);
		}
		$datas['username'] = addslashes($this->Post['username']);
		$datas['nickname'] = addslashes($this->Post['nickname']);

		if(strlen($this->Post['password'])<5) {
			$this->Messager("密码过短，请设置至少5位",-1);
		}
		if($this->Post['password']!=$this->Post['password2']) {
			$this->Messager("两次输入的密码不相同",-1);
		}
		$datas['password'] = $this->Post['password'];

		$this->DatabaseHandler->SetTable(TABLE_PREFIX.'members');

		if(($this->DatabaseHandler->Select('',"username='{$datas['username']}'")) || ($this->DatabaseHandler->Select('',"nickname='{$datas['username']}'")))
		{
			$this->Messager("用户名(<b>{$this->Post['username']}</b>)已经存在，<A HREF='javascript:history.go(-1)'>请选择其它用户名注册</A>",null);
		}

        if(($this->DatabaseHandler->Select('',"username='{$datas['nickname']}'")) || ($this->DatabaseHandler->Select('',"nickname='{$datas['nickname']}'")))
        {
            $this->Messager("姓名/昵称(<b>{$this->Post['nickname']}</b>)已经存在，<A HREF='javascript:history.go(-1)'>请选择其它姓名/昵称注册</A>",null);
        }


		$host=strstr($this->Post['email'],'@');
		if (stristr($this->Config['reg_email_forbid'],$host)!==false)
		{
			$this->Messager("由于您邮件服务提供商会过滤本站程序发送的有效邮件，请重新填写一个EMAIL地址。");
		}
		include(ROOT_PATH . 'include/lib/validate.han.php');
		$this->ValidateHandler=new ValidateHandler();
		$this->ValidateHandler->IsValid($this->Post['email'],'email','email格式错误','email');
		if($this->ValidateHandler->GetInvalidCount()!=0)
		{
			$this->Messager($this->ValidateHandler->GetInvalid());
		}

				if($this->Config["reg_email_doublee"]!= "1")
		{
			$this->DatabaseHandler->SetTable(TABLE_PREFIX.'members');
			$email_is_exists=$this->DatabaseHandler->Select('',"email='{$this->Post['email']}'");

			if($email_is_exists) $this->Messager("Email地址无效或已经存在");
		}
		$datas['email'] = $this->Post['email'];

		$datas['role_id']=$this->Config['normal_default_role_id'];

		$datas['password_unhash']=$datas['password'];
		$datas['password']=md5($datas['password']);

		$datas['province'] = $this->Post['province']; 		$datas['city'] = $this->Post['city'];
		$datas['regdate']=$datas['lastactivity']=$datas['lastvisit']=time();
		$datas['regip']=$datas['lastip']=client_ip();



		if($this->Config['reg_email_verify']==1)
		{
			$role_id_tmp=$this->Post['role_id'];

			$datas['role_id']=$this->Config['no_verify_email_role_id'];
		}


		$datas['address']=$zone_list[$area_id];
		$datas['area_id']=$this->MemberHandler->MemberFields['area_id'];
		

				if ($this->Config['extcredits_enable'])
		{
			foreach ($this->Config['credits']['ext'] as $_k=>$_v)
			{
				if ($_v['enable'] && $_v['default'])
				{
					$datas[$_k] = $_v['default'];
				}
			}
		}


		if(true === UCENTER) 		{
						include_once(ROOT_PATH . 'uc_client/client.php');

			$uc_result = uc_user_register($datas['username'],$datas['password_unhash'],$datas['email']);
			if($uc_result < 0)
			{
				if($uc_result > -4) $this->Messager("您输入的用户名无效或已被他人使用");
				if($uc_result > -7) $this->Messager("您输入的Email地址无效或已被他人使用");

				$this->Messager("新用户注册失败");
			}

			$datas['ucuid'] = $uc_result;
			$message['uc_login'] = uc_user_synlogin($uc_result);		}


		$this->DatabaseHandler->SetTable(TABLE_PREFIX . 'members');

		$uid=$this->DatabaseHandler->Insert($datas); 		if ($uid==false)
		{
			$this->Messager('插入用户数据出错。请与管理员联系。'.$this->Config['site_admin_email'],null);
		}
		$datas['uid']=$uid;

		$this->DatabaseHandler->SetTable(TABLE_PREFIX.'memberfields');
		$this->DatabaseHandler->Replace($datas);

				if($this->Config['reg_email_verify']==1)
		{
			Load::functions('my');

			my_member_validate($uid,$datas['email'],(int) ($role_id_tmp ? $role_id_tmp : $this->Config['normal_default_role_id']));
		}

				if ($this->Config['invite_enable']) {
			$u = $check_result['uid'];
			$c = $check_result['code'];
			if(0 < ($invite_id = $check_result['invite_id'])) {
				$sql = "select * from `".TABLE_PREFIX."invite` where `id`='{$invite_id}'";
				$query = $this->DatabaseHandler->Query($sql);
				$row = $query->GetRow();
				if ($row) {
					$sql = "update `".TABLE_PREFIX."invite` set `fuid`='{$uid}',`fusername`='{$datas['username']}' where `id`='{$row['id']}'";
					$this->DatabaseHandler->Query($sql);
				}
			} else {
				$sql = "insert into `".TABLE_PREFIX."invite` (`uid`,`code`,`dateline`,`fuid`,`fusername`,`femail`) values ('{$u}','{$c}','{$timestamp}','{$uid}','{$datas['username']}','{$datas['email']}')";
				$this->DatabaseHandler->Query($sql);
			}

			buddy_add($u,$uid);
			buddy_add($uid,$u);


						$sql = "update `".TABLE_PREFIX."members` set `invite_count`=`invite_count`+1 where `uid`='{$u}'";
			$this->DatabaseHandler->Query($sql);


						if ($this->Config['invite_enable'] > 1) {
				$sql = "select count(*) as code_invite_count from `".TABLE_PREFIX."invite` where `uid`='{$u}' and `code`='{$c}'";
				$query = $this->DatabaseHandler->Query($sql);
				extract($query->GetRow());

				if ($code_invite_count > $this->Config['invite_enable']) {
					$this->_checkInvite($u,1);
				}
			} else {
				$this->_checkInvite($u,1);
			}

			if($this->Config['extcredits_enable'] && $u > 0)
			{
				
				update_credits_by_action('register',$u);
			}
		}


		$authcode=authcode("{$datas['password']}\t{$uid}",'ENCODE');
		$this->CookieHandler->SetVar('auth',$authcode,($this->Config['cookie_expire']*86400));
		$this->CookieHandler->SetVar('sid','',-86400000);

		$referer=$this->CookieHandler->GetVar('referer');
		$this->CookieHandler->SetVar('referer','');


		if($this->Config['reg_email_verify']!='1')
		{
			$referer = $referer?$referer:referer();

			$this->Messager(null,'index.php?mod=member&code=step1',0);

			$message[]="您已经注册成功，现在系统将在10秒后自动为您转入<A HREF='index.php?mod=settings&code=face'>设置个人资料和头像的页面</A>。";
			$message[]="或者<A HREF='{$referer}' target=_blank>点此在新窗口中访问刚才的页面</A>。";
			$this->Messager($message,'index.php?mod=settings&code=face',10);

		}
		else
		{
			$this->DatabaseHandler->SetTable(TABLE_PREFIX.'role');
			$role=$this->DatabaseHandler->Select($this->Config['no_verify_email_role_id']);
			$message[]="确认 Email 已经发送，请用邮件中提供的方法激活您的帐号。";
			$message[]="注意：在完成激活之前，根据管理员设置，您将只能以<b>[{$role['name']}]</b>的身份访问本站.";
			$message[]="您的一些操作可能被限制。激活成功后，限制将自动取消。";
			$message[]="如果您没有收到我们发送的系统邮件，请在<A HREF='index.php?mod=setting' target=_blank>修改个人信息</a>页面中的下方选择“重新验证 Email有效性”，或尝试更换另外一个Email地址";
			$this->Messager($message,null);
		}

	}

	function Step1()
	{ 
		$this->ShowConfig = ConfigHandler::get('show');
		
		$day = 7;
		$time = $day * 86400;
		$limit = (int) $this->ShowConfig['reg_follow']['user'];
		if($limit < 1) $limit = 20;

		Load::logic('topic');
		$TopicLogic = new TopicLogic($this);

		if (false === ($uids = cache("misc/RTU-{$day}-{$limit}",900))) {
			$dateline = time() - $time;
			$sql = "SELECT DISTINCT(uid) AS uid, COUNT(tid) AS topics FROM `".TABLE_PREFIX."topic` WHERE dateline>=$dateline GROUP BY uid ORDER BY topics DESC LIMIT {$limit}";
			$query = $this->DatabaseHandler->Query($sql);
			$uids = array();
			while ($row = $query->GetRow())
			{
				$uids[$row['uid']] = $row['uid'];
			}

			cache($uids);
		}
		if(!$uids) {
			$uids[1] = 1;
		}

		$list = array();
		if($uids) {
			$_list = $TopicLogic->GetMember($uids,"`uid`,`ucuid`,`username`,`face_url`,`face`,`province`,`city`,`fans_count`,`topic_count`,`validate`,`nickname`");

			foreach ($uids as $uid) {
				if ($uid > 0 && isset($_list[$uid]) && $uid!=MEMBER_ID) {
					$list[$uid] = $_list[$uid];
				}
			}
		}


		$this->Title = "关注热门人物";
		include($this->TemplateHandler->Template('member_step1'));
	}
	function DoStep1()
	{
		$ids = (array) $this->Post['ids'];
		if(MEMBER_ID > 0 && $ids) {
			foreach ($ids as $id) {
				$id = (int) $id;
				if($id > 0) {
					buddy_add($id);
				}
			}
		}

	$this->Messager(null,$this->Config['site_url'].'/index.php?mod=member&code=step2',0);

	}

	function Step2()
	{

		$this->Title = '发布第一条微博';
		include($this->TemplateHandler->Template('member_step2'));
	}
	function DoStep2()
	{
		if (($content = $this->Post['content'])) {
			Load::logic('topic');
			$TopicLogic = new TopicLogic($this);
			$return = $TopicLogic->Add($content);

			if ($return['tid'] < 1) {
				$this->Messager(is_string($return) ? $return : "未知错误",'?');
			}
		}

		$this->Messager("注册成功",'index.php?mod=topic&code=myhome',0);
	}


	function _checkInvite($invite_code='',$reset=0)
	{
		$invite_code = $invite_code ? $invite_code : ($this->Post['invite_code'] ? $this->Post['invite_code'] : $this->Get['invite_code']);
		$invite_max = (int) $this->Config['invite_count_max'];
		$result = false;

		if($invite_code) {

			if(is_numeric($invite_code)) {
				$u = $invite_code;
			} else {
				$invite_code = str_replace(array('@','#',),'|',(string) $invite_code);
				list($u,$c) = explode('|',$invite_code);
			}

			if(($u = (int) $u) > 0) {
				$c_l = strlen(($c = trim($c)));

				if(32 == $c_l) {
					$sql = "select * from `".TABLE_PREFIX."invite` where `id`='{$u}'";
					$query = $this->DatabaseHandler->Query($sql);
					if (($row = $query->GetRow())) {
						$result = ($c==md5($row['id'].$row['code'].$row['dateline'].$row['femail']));
						$invite_id = $u;
						$u = $row['uid'];
						$c = $row['code'];
					}
				}

				$sql = "select `uid`,`invite_count`,`invitecode`,`role_type` from `".TABLE_PREFIX."members` where `uid`='{$u}'";
				$query = $this->DatabaseHandler->Query($sql);
				if(($row = $query->GetRow())) {
					if($c && !$result && ('admin' == $row['role_type'] || $invite_max < 1 || $invite_max >= $row['invite_count'])) {
						$result = ($row['invitecode'] == $c);

					}
				}

				if ($reset && $row['uid']>0) {
					$sql = "update `".TABLE_PREFIX."members` set `invitecode`='".(substr(md5($row['uid'] . $row['invitecode'] . random(16) . time()),0,16))."' where `uid`='{$row['uid']}'";
					$result = $this->DatabaseHandler->Query($sql);
				}
			}
		}
		$result = ($result ? array('uid'=>$u,'code'=>$c,'invite_id'=>$invite_id) : false);

		return $result;
	}

}

?>
